package com.ict.ms.trackPlayBack.facade.common;

import com.vividsolutions.jts.geom.Coordinate;

/**
 * Created by chitanda on 2017/10/29.
 */


public class CircularSectorWithLongitudeCrossed180 extends CircleWithLongitudeCrossed180 {

    private double startDir;
    private double endDir;

    public CircularSectorWithLongitudeCrossed180(double Longitude, double Latitude, double radiusInMeters, double startDirectionInDegree, double endDirectionInDegree) {
        super(Longitude,Latitude,radiusInMeters);
        startDir = startDirectionInDegree/180*3.1415926535;
        endDir = endDirectionInDegree/180*3.1415926535;
    }

    @Override
    public boolean containsPoint(double lon, double lat) {
        if(!super.containsPoint(lon, lat)){
            return false;
        }
        double curDir = getAngle(new Coordinate(lon,lat));
        if(startDir<=endDir)
            return curDir>=startDir && curDir<=endDir;
        else //0 degree is crossed
            return curDir>=startDir || curDir<=endDir;
    }


    public double getAngle(Coordinate p) {
//        Coordinate center = circle.getCenter();
//        double dx = p.x - center.x;
//        double dy = p.y - center.y;

        double dx;
        double dy;
        Coordinate center = circle.getCenter();
        double dx1 = super.distenceOf2Point(p.x,p.y,center.x,p.y);
        double dx2 = super.distenceOf2Point(p.x,center.y,center.x,center.y);
        if (p.x>=center.x)
        {
            dx = (dx1+dx2)/2;
        }
        else
        {
            dx = -((dx1+dx2)/2);
        }
        dy = super.distenceOf2Point(p.x,p.y,p.x,center.y);
        if (p.y < center.y)
        {
            dy = -dy;
        }




        double angle;
        if (dx == 0.0D) {
            if (dy == 0.0D) {
                angle = 0.0D;
            } else if (dy > 0.0D) {
                angle = 1.5707963267948966D;
            } else {
                angle = 4.71238898038469D;
            }
        } else if (dy == 0.0D) {
            if (dx > 0.0D) {
                angle = 0.0D;
            } else {
                angle = 3.141592653589793D;
            }
        } else if (dx > 0.0D && dy > 0.0D) {
            angle = -Math.atan(dy / dx) + 3.141592653589793D/2;
        } else if (dx > 0.0D && dy < 0.0D) {
            angle = Math.atan(-dy / dx) + 3.141592653589793D/2;
        } else if (dx < 0.0D && dy < 0.0D) {
            angle = -Math.atan(dy / dx) + 3.141592653589793D/2*3;
        } else {
            angle = Math.atan(dy / -dx) + 3.141592653589793D/2*3  ;
        }

        return angle;
    }
}
